<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Common
 *
 * @author wangnaixin
 */
function ApiCall($roule,$params=[]){
    if(!empty($roule)){
    	if (IS_AJAX) {
	    	session('returnArray','1');
    	}
        $resultJson = R("Api/".$roule,$params);
        if (IS_AJAX) {
	        session('returnArray',null);
        }
        return $resultJson;
    }else{
        return false;
    }
}

function getPage($count, $pagesize = 20) {
    $p = new Think\Page($count, $pagesize);
    //$p->setConfig('header', '共<b>%TOTAL_ROW%</b>条记录&nbsp;第<b>%NOW_PAGE%</b>页/共<b>%TOTAL_PAGE%</b>页');
    $p->setConfig('prev', '<');
    $p->setConfig('next', '>');
    /*$p->setConfig('prev', '<span aria-hidden="true">&laquo;</span>');
    $p->setConfig('next', '<span aria-hidden="true">&raquo;</span>');*/
   //$p->setConfig('last', '末页');
   //$p->setConfig('first', '首页');
//    $p->setConfig('theme', '%FIRST%%UP_PAGE%%LINK_PAGE%%DOWN_PAGE%%END%%HEADER%');
//    $p->lastSuffix = true;//最后一页不显示为总页数
    return $p;
}

function getCateName($id){
    $newsCate = new \Admin\Model\NewsCateModel();
    $cateInfo = $newsCate->getCateInfoById($id);
    return $cateInfo['cate_name'];
}

function getUserName($id){
    $userModel = new Admin\Model\UserModel();
    $userInfo = $userModel->getUserInfoById($id);
    return  $userInfo['real_name'];
}

function getAvatar($id){
    $userModel = new Admin\Model\UserModel();
    $userInfo = $userModel->getUserInfoById($id);
    $avatar = $userInfo['avatar'];
    if (!$avatar) {
        $avatar = __ROOT__.'/Public/images/avatar.png';
    } else if (!preg_match('/^(http:|https:)/i',$avatar)) {
        if (!file_exists($avatar)) {
            $avatar = __ROOT__.'/Public/images/avatar.png';
        }
    }
    return $avatar;
}

function _menuInit($data){
    $menuList = [];
    foreach($data as $val){
        if($val['pid'] == "0" && $val['ismenu'] == "1"){
            $subMenu = array();
            foreach ($data as $v){
                if($val['id'] == $v['pid'] && $v['ismenu'] == 1){
                    $subMenu[$v['order']]=array(
                        'menuName' =>$v['menuname'],
                        'url'=>$v['url'],
                        'controller'=>$v['controller'],
                        'function'=>$v['function']
                    );
                }
            }
            ksort($subMenu);
            $menuList[$val['order']] = array(
                'menuName' =>$val['menuname'],
                'url'=>$val['url'],
                'icon'=>$val['icon'],
                'controller'=>$val['controller'],
                'function'=>$val['function'],
                'subMenu'=>$subMenu
            );
        }
    }
    ksort($menuList);
    return $menuList;
}

function menuInit($data){
    $menuList = [];
    foreach($data as $val){
        if($val['pid'] == "0" && $val['ismenu'] == "1"){
            $subMenu = array();
            foreach ($data as $v){
                if($val['id'] == $v['pid'] && $v['ismenu'] == 1){
                    $subMenu[$v['order']]=array(
                        'menuName' =>$v['menuname'],
                        'url'=>$v['url'],
                        'controller'=>$v['controller'],
                        'function'=>$v['function']
                    );
                }
            }

            ksort($subMenu);
            $menuList[$val['order']] = array(
                'menuName' =>$val['menuname'],
                'url'=>$val['url'],
                'icon'=>$val['icon'],
                'controller'=>$val['controller'],
                'function'=>$val['function'],
                'subMenu'=>$subMenu
            );
        }
    }
    ksort($menuList);
    return $menuList;
}

function authInit($data){
   $authList = [];

   foreach ($data as $v){
       if(!empty($v['function'])){
           $authList[$v['controller']][] = $v['function'];
       }
   }
   return $authList;

}

//发送用户注册短信验证码
function sendRegisterCode($mobile,$code){
	$content = sprintf('#code#=%s',$code);
	return sendSMS($mobile,42061,$content);
}

//发送用户密码重置短信验证码
function sendPwdResetCode($mobile,$code){
	$content = sprintf('#code#=%s',$code);
	return sendSMS($mobile,42062,$content);
}

/**
 * 发送物业费催缴通知（企业方）
 * @param $mobile 手机号
 * @param $companyName 企业名称
 * @param $nextPayDate 缴费期限
 * @return array
 */
function sendCondoFeeNoticeToCompany($mobile,$companyName,$nextPayDate) {
    $content = sprintf('#companyName#=%s&#nextPayDate#=%s',$companyName,$nextPayDate);
    return sendSMS($mobile,64968,$content);
}

/**
 * 发送物业费催缴通知（物管方）
 * @param $mobile 手机号
 * @param $companyName 企业名称
 * @param $nextPayDate 缴费期限
 * @return array
 */
function sendCondoFeeNoticeToAdmin($mobile,$companyName,$nextPayDate) {
    $content = sprintf('#companyName#=%s&#nextPayDate#=%s',$companyName,$nextPayDate);
    return sendSMS($mobile,64969,$content);
}

function sendSMS($mobile,$tpl_id='',$tpl_value=''){
	$rs = array('status' => false);
	$smsConfig = C('SMS_CONFIG');
	$smsConf = array(
		'key'   	=> $smsConfig['key'],
		'mobile'    => $mobile,
		'tpl_id'    => $tpl_id,
		'tpl_value' => urlencode($tpl_value)
	);
	$response = getHttpContent($smsConfig['url'],$smsConf,1);
	if($response){
		$result = json_decode($response,true);
		$error_code = $result['error_code'];
		if($error_code == 0){
			//状态为0，说明短信发送成功
			$rs['status'] = true;
			$rs['msg'] = '短信发送成功!';
		}else{
			//状态非0，说明失败
			$rs['msg'] = '短信发送失败('.$error_code.')：'.$result['reason'];
		}
	}else{
		//返回内容异常，以下可根据业务逻辑自行修改
		$rs['msg'] = '短信发送失败，请稍后再试';
	}
	return $rs;
}

function getHttpContent($url,$params=false,$ispost=0){
	$httpInfo = array();
	$ch = curl_init();
	curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
	curl_setopt( $ch, CURLOPT_USERAGENT , 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22');
	curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 30 );
	curl_setopt( $ch, CURLOPT_TIMEOUT , 30);
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
	if( $ispost )
	{
		curl_setopt( $ch , CURLOPT_POST , true );
		curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );
		curl_setopt( $ch , CURLOPT_URL , $url );
	}
	else
	{
		if($params){
			curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params );
		}else{
			curl_setopt( $ch , CURLOPT_URL , $url);
		}
	}
	$response = curl_exec( $ch );
	if ($response === FALSE) {
		//echo "cURL Error: " . curl_error($ch);
		return false;
	}
	$httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
	$httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
	curl_close( $ch );
	return $response;
}

/**
 * 生成行号
 * @param number $index 记录索引，从0开始
 * @param number $curPage 当前页，从1开始
 * @param number $pageSize 每页大小
 * @return number
 */
function getLineNum($index=0,$curPage=1,$pageSize=1){
    $start = ($curPage - 1) * $pageSize;
    $line = $start + $index + 1;
    return $line;
}
//文件名
/**
 * 获取缩略图
 * @param unknown_type $filename 原图路劲、url
 * @param unknown_type $width 宽度
 * @param unknown_type $height 高
 * @param unknown_type $cut 是否切割 默认不切割
 * @return string
 */
function getThumbImage($filename, $width = 100, $height = 'auto', $type,$cut = false, $replace = false) {
    $UPLOAD_PATH = C('ATTACHMENT_PATH');
    //$filename = str_ireplace(UPLOAD_URL.$type.'/'.$filename, '', $filename); //将URL转化为本地地址
    $info = pathinfo($filename);

    $oldFile = $type . DIRECTORY_SEPARATOR  . $info['filename'] . '.' . $info['extension'];

    $thumbFile = $type . DIRECTORY_SEPARATOR  .$info['filename'] . '_' . $width . '_' . $height . '.' . $info['extension'];

    $oldFile = str_replace('\\', '/', $oldFile);

    $thumbFile = str_replace('\\', '/', $thumbFile);


 /*   $filename = '/' . ltrim($filename, '/');
    $oldFile = '/' . ltrim($oldFile, '/');
    $thumbFile = '/' . ltrim($thumbFile, '/');*/
//原图不存在直接返回
    if (!file_exists($UPLOAD_PATH . $oldFile)) {

        @unlink($UPLOAD_PATH . $thumbFile);
        $info['src'] = $oldFile;
        $info['width'] = intval($width);
        $info['height'] = intval($height);
        return $info;
//缩图已存在并且 replace替换为false
    } elseif (file_exists($UPLOAD_PATH . $thumbFile) && !$replace) {
        $imageinfo = getimagesize($UPLOAD_PATH . $thumbFile);
        $info['src'] = $thumbFile;
        $info['width'] = intval($imageinfo[0]);
        $info['height'] = intval($imageinfo[1]);
        return $info;
//执行缩图操作
    } else {
        $oldimageinfo = getimagesize($UPLOAD_PATH . $oldFile);

        $old_image_width = intval($oldimageinfo[0]);
        $old_image_height = intval($oldimageinfo[1]);
        if ($old_image_width <= $width && $old_image_height <= $height) {
            @unlink($UPLOAD_PATH . $thumbFile);
            @copy($UPLOAD_PATH . $oldFile, $UPLOAD_PATH . $thumbFile);
            $info['src'] = $thumbFile;
            $info['width'] = $old_image_width;
            $info['height'] = $old_image_height;
            return $info;
        } else {

//生成缩略图 - 更好的方法
            if ($height == "auto")
                $height = 0;
            Vendor('phpthumb.ThumbLib#inc');
            $thumb = \PhpThumbFactory::create($UPLOAD_PATH . $type.'/'.$filename);
            if ($cut) {
                $thumb->adaptiveResize($width, $height);
            } else {
                $thumb->resize($width, $height);
            }
            $res = $thumb->save($UPLOAD_PATH . $thumbFile);
//缩图失败
            if (!$res) {
                $thumbFile = $oldFile;
            }
            $info['width'] = $width;
            $info['height'] = $height;
            $info['src'] = $thumbFile;
            return $info;
        }
    }
}

/**
 * 对应于上面的方法，纯粹只处理图片的缩略图路径
 * @param type $filename
 * @param type $width
 * @param type $height
 * @return type
 */
function getThumbImageUrl($filename, $width = '100', $height = 'auto'){
    $src = '';
    if(!empty($filename)){
        //if(!is_numeric($width) || $width < 20 || (is_numeric($height) && $height < 20) || $height != 'auto'){
        // return false;
        //}
        $ss = explode('.', $filename);
        $src = $ss[0].'_'.$width . '_' . $height.'.'.$ss[1];
    }

    return $src;
}

/**
 * 字符串截取，支持中文和其他编码
 * @param string $str 需要转换的字符串
 * @param int $start 开始位置
 * @param string $length 截取长度
 * @param string $charset 编码格式
 * @param boolean $suffix 截断显示字符
 * @return string
 */
function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true) {
    $strLen = 0;
    if (function_exists("mb_substr")) {
        $slice = mb_substr($str, $start, $length, $charset);
        $strLen = mb_strlen($str, $charset);
    } elseif(function_exists('iconv_substr')) {
        $slice = iconv_substr($str,$start,$length,$charset);
        $strLen = iconv_strlen($str, $charset);
    } else {
        $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
        $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
        $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
        $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
        preg_match_all($re[$charset], $str, $match);
        $slice = implode("",array_slice($match[0], $start, $length));
        $strLen = strlen($slice);
    }
    return $suffix && $strLen>$length ? $slice.'...' : $slice;
}

/**
 * 将年度税收和营业额按月随机拆分
 * @param $turnover 营业额
 * @param $taxAmount 税收
 * @param $year 税收年度 如 2017
 * @param int $months 总月份，可选值：1 - 12
 * @return array
 */
function splitTaxByMonth($turnover,$taxAmount,$year,$months=12) {
    $data = array();
    $percent = array();
    //如果只有一个月的税收数据，不作拆分，直接返回
    if ($months == 1) {
        $data[$year.'-'.sprintf('%02s', $months)] = array(
            'turnover' => sprintf('%.2f',$turnover),
            'taxAmount' => sprintf('%.2f',$taxAmount)
        );
        return $data;
    }
    //随机拆分处理
    while (true) {
        if (count($percent) >= $months) {
            break;
        }
        //每个月的税收比例，在5%-35%之间随机生成
        $randNum = mt_rand(5, 35);
        //确保生成的随机数没有重复
        if (in_array($randNum,$percent)) {
            continue;
        }
        $percent[] = $randNum;
    }
    $sum = array_sum($percent);
    //打乱每个月的税收比例，随机分配
    shuffle($percent);
    //删除最后一个月的税收比例
    array_pop($percent);
    $turnoverSum = 0;
    $taxAmountSum = 0;
    foreach ($percent as $m => $per) {
        $ratio = $per/$sum;
        $turnoverMonth = sprintf('%.2f',$turnover*$ratio);
        $taxAmountMonth = sprintf('%.2f',$taxAmount*$ratio);
        $data[$year.'-'.sprintf('%02s', $m+1)] = array(
            'turnover' => $turnoverMonth,
            'taxAmount' => $taxAmountMonth
        );
        $turnoverSum += $turnoverMonth;
        $taxAmountSum += $taxAmountMonth;
    }
    //防止精度损失，最后一个月的税收和营业额，用总额减去前面几个月的总和
    $data[$year.'-'.sprintf('%02s', $months)] = array(
        'turnover' => sprintf('%.2f',$turnover-$turnoverSum),
        'taxAmount' => sprintf('%.2f',$taxAmount-$taxAmountSum)
    );
    return $data;
}

/**
 * 获取当前周的起止日期
 * @return array
 */
function getCurWeek($curTime=null) {
    $defaultDate = $curTime ? : date('Y-m-d');
    //1 表示每周星期一为开始日期 0表示每周日为开始日期
    $first = 1;
    //获取当前周的第几天 周日是 0 周一到周六是 1 - 6
    $w = date('w',strtotime($defaultDate));
    //获取本周开始日期，如果$w是0，则表示周日，减去 6 天
    $start = date('Y-m-d',strtotime("$defaultDate -".($w ? $w - $first : 6).' day'));
    //本周结束日期
    $end = date('Y-m-d',strtotime("$start +6 day"));
    return array('start' => $start,'end' => $end);
}

/**
 * 获取上一周的起止日期
 * @param null $curTime
 * @return array
 */
function getPrevWeek($curTime=null) {
    $curTime = $curTime ? : time();
    $start = date('Y-m-d',strtotime("$curTime - 7 day"));
    $end = date('Y-m-d',strtotime("$curTime - 1 day"));
    return array('start' => $start,'end' => $end);
}

/**
 * 获取下一周的起止日期
 * @param null $curTime
 * @return array
 */
function getNextWeek($curTime=null) {
    $curTime = $curTime ? : time();
    $start = date('Y-m-d',strtotime("$curTime + 7 day"));
    $end = date('Y-m-d',strtotime("$curTime + 13 day"));
    return array('start' => $start,'end' => $end);
}

/**
 * 获取每一周的连续日期
 * @param $start
 * @param $end
 * @return array
 */
function getWeekRange($start,$end) {
    $weeks = array('周日','周一','周二','周三','周四','周五','周六');
    $weekRange = array();
    $days = floor((strtotime($end)-strtotime($start))/86400);
    for ($i=0;$i<=$days;$i++) {
        $day = date('Y-m-d',strtotime($start.' '.$i.' day'));
        $weekRange[] = array(
            'day' => date('m-d',strtotime($day)),
            'week' => $weeks[date('w',strtotime($day))],
            'start' => $start,
            'fullDay' => $day
        );
    }
    return $weekRange;
}

/**
 * 发送微信模板通知
 * @param $data 模板数据
 * @return array|bool
 */
function sendWenXinNotice($data) {
    vendor('WeiXinSDK.wechat','','.class.php');
    $options = array(
        'appid' => C('appId'),
        'appsecret' => C('appSecret')
    );
    $weObj = new \Wechat($options);
    $result = $weObj->sendWxTemplateMessage($data);
    return array('result' => $result,'weObj' => $weObj);
}

/**
 * 跨域访问设置
 * @param array $allowOrigin 允许的跨域域名列表
 */
function crossDomain($allowOrigin=array()) {
    //跨域访问的时候才会存在此字段
    $origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
    if(in_array($origin, $allowOrigin)){
        header('Access-Control-Allow-Origin:'.$origin);
        header('Access-Control-Allow-Methods:POST,GET');
        header('Access-Control-Allow-Headers:x-requested-with,content-type');
    }
}

/**
 * 更新附件地址
 * 
 */
function checkAttUrl($data){
    $res =   str_replace("qixia.sycx.jc-jt.com/","qixia.sycx.jc-jt.com:8081/",$data);
    return preg_replace('/(src=\")(\/upload\/)/',"\${1}".C('IMG_PATH')."/upload/\${3}",$res);
    
}
